/*
 * Copyright (c) 2006-2022, Ulandlink Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-10-31     xpw          first version
 */

#include <stdio.h>
#include <string.h>

#include <at_device_w15.h>

#define LOG_TAG               "at.skt.w15"
#define LOG_LVL               LOG_LVL_DBG
#include <at_log.h>

#if defined(AT_DEVICE_USING_W15) && defined(AT_USING_SOCKET)

/* show received data */
#define W15_RECV_DATA_SHOW_ENABLE 0

/* show urc message */
#define W15_URC_MSG_SHOW_ENABLE  0

#define W15_MODULE_SEND_MAX_SIZE   2000
#define W15_MODULE_RECV_MAX_SIZE   2000


/* set real event by current socket and current state */
#define SET_EVENT(socket, event)       (((socket + 1) << 16) | (event))

/* AT socket event type */
#define W15_EVENT_CONN_OK          (1L << 0)
#define W15_EVENT_SEND_OK          (1L << 1)
#define W15_EVENT_RECV_OK          (1L << 2)
#define W15_EVNET_CLOSE_OK         (1L << 3)
#define W15_EVENT_CONN_FAIL        (1L << 4)
#define W15_EVENT_SEND_FAIL        (1L << 5)

#define W15_RECEIVE_DATA_WORK_NAME  "w15_work"

static w15_recv_t recv_urc_idct;

static rt_int32_t w15_socket_fd[AT_DEVICE_W15_SOCKETS_NUM];

static at_evt_cb_t at_evt_cb_set[] = {
        [AT_SOCKET_EVT_RECV] = NULL,
        [AT_SOCKET_EVT_CLOSED] = NULL,
};

static int w15_socket_event_send(struct at_device *device, uint32_t event)
{
    return (int) rt_event_send(device->socket_event, event);
}

static int w15_socket_event_recv(struct at_device *device, uint32_t event, uint32_t timeout, rt_uint8_t option)
{
    int result = 0;
    rt_uint32_t recved;

    result = rt_event_recv(device->socket_event, event, option | RT_EVENT_FLAG_CLEAR, timeout, &recved);
    if (result != RT_EOK){
        return -RT_ETIMEOUT;
    }

    return recved;
}

/**
 * close socket by AT commands.
 *
 * @param current socket
 *
 * @return  0: close socket success
 *         -1: send AT commands error
 *         -2: wait socket event timeout
 *         -5: no memory
 */
static int w15_socket_close(struct at_socket *socket)
{
    int result = RT_EOK;
    at_response_t resp = RT_NULL;
    int device_socket = (int) socket->user_data;
    struct at_device *device = (struct at_device *) socket->device;
    int wsk = w15_socket_fd[device_socket];

    w15_socket_fd[device_socket] = -1;
    
    resp = at_create_resp(64, 0, RT_TICK_PER_SECOND);
    if (resp == RT_NULL){
        LOG_E("no memory for resp create.");
        return -RT_ENOMEM;
    }

    result = at_obj_exec_cmd(device->client, resp, "AT+UDCPC=%d", wsk);

    if (resp){
        at_delete_resp(resp);
    }

    return result;
}

/**
 * create TCP/UDP client or server connect by AT commands.
 *
 * @param socket current socket
 * @param ip server or client IP address
 * @param port server or client port
 * @param type connect socket type(tcp, udp)
 * @param is_client connection is client
 *
 * @return   0: connect success
 *          -1: connect failed, send commands error or type error
 *          -2: wait socket event timeout
 *          -5: no memory
 */
static int w15_socket_connect(struct at_socket *socket, char *ip, int32_t port, enum at_socket_type type, rt_bool_t is_client)
{
    uint32_t event = 0;
    int socket_fd = -1;
    int result = RT_EOK;
    int event_result = 0;
    rt_bool_t retryed = RT_FALSE;
    at_response_t resp = RT_NULL;
    int device_socket = (int) socket->user_data;
    struct at_device *device = (struct at_device *) socket->device;

    RT_ASSERT(ip);
    RT_ASSERT(port >= 0);

    resp = at_create_resp(128, 0, 10 * RT_TICK_PER_SECOND);
    if (resp == RT_NULL){
        LOG_E("no memory for resp create.");
        return -RT_ENOMEM;
    }

__retry:
    
    event = SET_EVENT(device_socket, W15_EVNET_CLOSE_OK | W15_EVENT_CONN_FAIL);
    w15_socket_event_recv(device, event, 0, RT_EVENT_FLAG_OR);
    
    if (is_client){
        switch (type) {
            case AT_SOCKET_TCP:
                if (at_obj_exec_cmd(device->client, resp, "AT+UDCP=at-tcp://%s:%d", ip, port) < 0){
                    result = -RT_ERROR;
                    goto __exit;
                }
                break;

            case AT_SOCKET_UDP:
                if (at_obj_exec_cmd(device->client, resp, "AT+UDCP=at-udp://%s:%d", ip, port) < 0){
                    result = -RT_ERROR;
                    goto __exit;
                }
                break;

            default:
                LOG_E("device(%s) not supported connect type %d.", device->name, type);
                result = -RT_ERROR;
                goto __exit;
        }
    }
     
    if (at_resp_parse_line_args_by_kw(resp, "+UDCP:", "+UDCP:%d", &socket_fd) <= 0) {
        LOG_E("device(%s) parse socket id failed.", device->name);
        goto __exit;
    }
    
    w15_socket_fd[device_socket] = socket_fd;
    LOG_D("get device(%s) peers id(%d)", device->name, socket_fd);
    
    /* waiting result event from AT URC */
    if (w15_socket_event_recv(device, SET_EVENT(socket_fd, 0), 30 * RT_TICK_PER_SECOND, RT_EVENT_FLAG_OR) < 0) {
        LOG_E("device(%s) socket(%d) connect failed, wait connect result timeout.", device->name, socket_fd);
        at_obj_exec_cmd(device->client, resp, "AT+UDCPC=%d", socket_fd);
        result = -RT_ETIMEOUT;
        goto __exit;
    }
    
    /* waiting OK or failed result */
    event_result = w15_socket_event_recv(device, W15_EVENT_CONN_OK | W15_EVENT_CONN_FAIL, 1 * RT_TICK_PER_SECOND, RT_EVENT_FLAG_OR);
    if (event_result < 0) {
        LOG_E("device(%s) socket(%d) connect failed, wait connect OK|FAIL timeout.", device->name, socket_fd);
        at_obj_exec_cmd(device->client, resp, "AT+UDCPC=%d", socket_fd);
        result = -RT_ETIMEOUT;
        goto __exit;
    }
    
    /* check result */
    if (event_result & W15_EVENT_CONN_FAIL) {
        if (retryed == RT_FALSE) {
            LOG_D("device(%s) socket(%d) connect failed, maybe the socket was not be closed at the last time and now will retry.", device->name, socket_fd);
            retryed = RT_TRUE;
            goto __retry;
        }
        LOG_E("device(%s) socket(%d) connect failed.", device->name, socket_fd);
        result = -RT_ERROR;
        goto __exit;
    }
    
__exit:
    
    if (resp){
        at_delete_resp(resp);
    }

    return result;
}

/**
 * send data to server or client by AT commands.
 *
 * @param socket current socket
 * @param buff send buffer
 * @param bfsz send buffer size
 * @param type connect socket type(tcp, udp)
 *
 * @return >=0: the size of send success
 *          -1: send AT commands error or send data error
 *          -2: waited socket event timeout
 *          -5: no memory
 */
static int w15_socket_send(struct at_socket *socket, const char *buff, size_t bfsz, enum at_socket_type type)
{
#define W15_SEND_RETRY_TIMEOUT 20
    
    int retry = 0;
    char temp[10] = {0};
    int result = RT_EOK;
    int event_result = 0;
    int timeout = W15_SEND_RETRY_TIMEOUT;
    at_response_t resp = RT_NULL;
    size_t cur_pkt_size = 0, sent_size = 0;
    int device_socket = (int) (socket->user_data);
    struct at_device *device = (struct at_device *) socket->device;
    struct at_device_w15 *w15 = (struct at_device_w15 *) device->user_data;

    RT_ASSERT(buff);
    RT_ASSERT(bfsz > 0);

    resp = at_create_resp(1280, 3, RT_TICK_PER_SECOND);
    if (resp == RT_NULL){
        LOG_E("no memory for resp create.");
        return -RT_ENOMEM;
    }
    
    at_obj_set_end_sign(device->client, '>');
    
    rt_mutex_take(device->client->lock, RT_WAITING_FOREVER);

    while (sent_size < bfsz){
        if (bfsz - sent_size < W15_MODULE_SEND_MAX_SIZE){
            cur_pkt_size = bfsz - sent_size;
        } else {
            cur_pkt_size = W15_MODULE_SEND_MAX_SIZE;
        }
        
        while (1) {
            /* send the "AT+UDATW" commands to AT server than receive the '>' response on the first line */
            if (at_obj_exec_cmd(device->client, resp, "AT+UDATW=%d,2,%d", w15_socket_fd[device_socket], cur_pkt_size) < 0){
                if (retry >= 100) {
                    rt_kprintf("device(%s) requests to send data failed and retry failed.", device->name);
                    rt_kprintf("system blocked.");
										while(1);
										result = -RT_ERROR;
                    goto __exit;
                }
                LOG_W("device(%s) requests to send data failed, retry...", device->name);
                rt_thread_mdelay(20);
                retry ++;
                continue;
            }
            retry = 0;
            break;
        }

        /* send the real data to server or client */
        result = (int) at_client_obj_send(device->client, buff + sent_size, cur_pkt_size);
        if (result == 0){
            result = -RT_ERROR;
            goto __exit;
        }
				//LOG_D("send %d bytes but I dont know if success.", result);
        
        sent_size += cur_pkt_size;
        rt_thread_mdelay(20);
    }

__exit:
    at_obj_set_end_sign(device->client, 0);
    rt_mutex_release(device->client->lock);

    if (resp){
        at_delete_resp(resp);
    }
    
    return result > 0 ? sent_size : result;
}

/**
 * domain resolve by AT commands.
 *
 * @param name domain name
 * @param ip parsed IP address, it's length must be 16
 *
 * @return  0: domain resolve success
 *         -2: wait socket event timeout
 *         -5: no memory
 */
static int w15_domain_resolve(const char *name, char ip[16])
{
#define RESOLVE_RETRY               3
#define W15_GET_PING_RESP_TIMEOUT   10 * RT_TICK_PER_SECOND

    int i, start_time;
    char *ping_resp_str;
    int result = RT_EOK;
    char recv_ip[16] = {0};
    at_response_t resp = RT_NULL;
    struct at_device *device = RT_NULL;

    RT_ASSERT(name);
    RT_ASSERT(ip);
    
    rt_memset(ip, 0, 16);

    device = at_device_get_first_initialized();
    if (device == RT_NULL){
        LOG_E("get first init device failed.");
        return -RT_ERROR;
    }

    resp = at_create_resp(128, 0, 30 * RT_TICK_PER_SECOND);
    if (resp == RT_NULL){
        LOG_E("no memory for resp create.");
        return -RT_ENOMEM;
    }
    
    for (i = 0; i < RESOLVE_RETRY; i++) {
        w15_ping_resp_clear();
        if (at_obj_exec_cmd(device->client, resp, "AT+UPING=\"%s\",1", name) < 0) {
            result = -RT_ERROR;
            continue;
        }
    
        start_time = rt_tick_get();

        while (1) {
            if (rt_tick_get() - start_time > W15_GET_PING_RESP_TIMEOUT) {
                break;
            }
            
            ping_resp_str = w15_ping_resp_get();
            if (*ping_resp_str != '\0') {
                break;
            }
            
            rt_thread_mdelay(300);
        }

        if (rt_strstr(ping_resp_str, "+UUPING:") != RT_NULL) {
            sscanf(ping_resp_str, "+UUPING:%*d,%*d,\"%*[^,],\"%[^\"]\",%*d,%*d", recv_ip);
            result = RT_EOK;
            break;
        } else if (rt_strstr(ping_resp_str, "+UUPINGER:") != RT_NULL) {
            result = RT_EOK;
            continue;
        }
    }
    
    if (rt_strlen(recv_ip) >= 8) {
        rt_strncpy(ip, recv_ip, 15);
    }
    
__exit:
    
    if (resp){
        at_delete_resp(resp);
    }

    return result;
}

/**
 * set AT socket event notice callback
 *
 * @param event notice event
 * @param cb notice callback
 */
static void w15_socket_set_event_cb(at_socket_evt_t event, at_evt_cb_t cb)
{
    if (event < sizeof(at_evt_cb_set) / sizeof(at_evt_cb_set[1])){
        at_evt_cb_set[event] = cb;
    }
}

static const struct at_socket_ops w15_socket_ops =
{
    w15_socket_connect,
    w15_socket_close,
    w15_socket_send,
    w15_domain_resolve,
    w15_socket_set_event_cb,
#if defined(AT_SW_VERSION_NUM) && AT_SW_VERSION_NUM > 0x10300
    RT_NULL,
#endif
};

static void w15_reqst_data_thread(void *parameter)
{
    int peer_id = 0;
    int length = 0;
    int index = -1;
    char *start_ptr;
    int temp_size = 0;
    char temp[8] = {0};
    char cmd[32] = {0};
    w15_recv_t recv_info;
    char size_str[8] = {0};
    char *buffer = RT_NULL;
    int ret, bfsz, timeout;
    char *recv_buf = RT_NULL;
    int wsk, socket_index = -1;
    at_response_t resp = RT_NULL;
    struct at_device *device = RT_NULL;
    struct at_client *client = RT_NULL;
    struct at_socket *socket = RT_NULL;
    struct at_socket *at_socket = RT_NULL;
    
    device = at_device_get_by_name(AT_DEVICE_NAMETYPE_NETDEV, W15_DEIVCE_NAME);
    if (device == RT_NULL) {
        LOG_E("get device(%s) failed.", W15_DEIVCE_NAME);
        return;
    }
    
    resp = at_create_resp(256, 0, RT_TICK_PER_SECOND/2);
    if (resp == RT_NULL ) {
        LOG_E("no memory for resp create.");
        return;
    }
    
    while (1) {
        for (int i = 0; i < AT_DEVICE_W15_SOCKETS_NUM - 1; i ++) {
            if (recv_urc_idct.peer_id[i] > 0) {
                peer_id = i + 1;
                length = recv_urc_idct.peer_id[i];
                
                if (length > W15_MODULE_RECV_MAX_SIZE) {
                    length = W15_MODULE_RECV_MAX_SIZE;
                }
                
                rt_mutex_take(&recv_urc_idct.lock, RT_WAITING_FOREVER);
                
                if (at_obj_exec_cmd(device->client, resp, "AT+UDATR=%d,2,%d", peer_id, length) < 0) {
                    LOG_W("device(%s) reqst data failed.", device->name);
                } else {
                    recv_urc_idct.peer_id[i] = 0;
                }
                rt_mutex_release(&recv_urc_idct.lock);                
            }
            rt_thread_mdelay(10);
        }
    }
}

static void urc_recv_data_func(struct at_client *client, const char *data, rt_size_t size)
{
    int ret;
    char size_str[8] = {0};
    rt_int32_t timeout = 0;
    int wsk, socket_index = -1;
    rt_size_t bfsz = 0, temp_size = 0;
    char *recv_buf = RT_NULL, temp[32] = {0};
    struct at_socket *socket = RT_NULL;
    struct at_device *device = RT_NULL;
    
#if W15_URC_MSG_SHOW_ENABLE
    LOG_D("get urc: %.*s", size, data);
#endif    
    
    device = at_device_get_by_name(AT_DEVICE_NAMETYPE_NETDEV, W15_DEIVCE_NAME);
    if (device == RT_NULL) {
        LOG_E("get device(%s) failed.", W15_DEIVCE_NAME);
        return;
    }
    
    /* get the at deveice socket and receive buffer size by receive data */
    sscanf(data, "AT+UDATR=%d,%*[^,],%d:", &wsk, (int *) &bfsz);
    
    if (bfsz == 0) {
        return;
    }
        
    /* set receive timeout by receive buffer length, not less than 10ms */
    timeout = bfsz > 10 ? bfsz : 10;  

    recv_buf = (char *) rt_calloc(1, bfsz);
    if (recv_buf == RT_NULL)
    {
        LOG_E("no memory receive buffer(%d).", bfsz);
        /* read and clean the coming data */
        while (temp_size < bfsz)
        {
            if (bfsz - temp_size > sizeof(temp))
            {
                at_client_obj_recv(client, temp, sizeof(temp), timeout);
            }
            else
            {
                at_client_obj_recv(client, temp, bfsz - temp_size, timeout);
            }
            temp_size += sizeof(temp);
        }
        return;
    }
    
    rt_snprintf(size_str, sizeof(size_str), "%d", bfsz);
    at_client_obj_recv(client, temp, 11 + strlen(size_str), timeout);
    if (rt_strstr(temp, "ERROR")) {
        rt_mutex_take(&recv_urc_idct.lock, RT_WAITING_FOREVER);
        recv_urc_idct.peer_id[wsk - 1] = bfsz;
        rt_mutex_release(&recv_urc_idct.lock);
        LOG_E("device(%s) receive size(%d) data failed, get ERROR", device->name, bfsz);
        rt_free(recv_buf);
        return;
    }

    /* sync receive data */
    ret = at_client_obj_recv(client, recv_buf, bfsz, timeout);
    if (ret != bfsz)
    {
        rt_kprintf("device(%s) receive size(%d) data failed, ret is %d.", device->name, bfsz, ret);
        rt_kprintf("system blocked");
			  while(1);
				rt_free(recv_buf);
        return;
    }
    
    at_client_obj_recv(client, temp, 2, timeout);;
    
    /* find at socket index matched to the peers id from urc */
    for (int i = 0; i < AT_DEVICE_W15_SOCKETS_NUM; i++)
    {
        if (wsk == w15_socket_fd[i])
        {
            socket_index = i;
            break;
        }
    }

    if (socket_index < 0) {
        LOG_E("received data from peers id(%d) discarded.", wsk);
        return;
    }

    /* get at socket object by device socket descriptor */
    socket = &(device->sockets[socket_index]);

    /* notice the receive buffer and buffer size */
    if (at_evt_cb_set[AT_SOCKET_EVT_RECV])
    {
        at_evt_cb_set[AT_SOCKET_EVT_RECV](socket, AT_SOCKET_EVT_RECV, recv_buf, bfsz);
    }
    
#if W15_RECV_DATA_SHOW_ENABLE    
    rt_kprintf("\n********* %s received %d bytes on socket %d *********\n",device->name, bfsz, wsk);
    for (int i = 0; i < bfsz; i ++) {
        rt_kprintf("%c", *(recv_buf + i));
    }
    rt_kprintf("\n********************************************************\n");
#endif
}

static void urc_connect_func(struct at_client *client, const char *data, rt_size_t size)
{
#define AT_ADDR_LEN 32

    int socket_index = -1;
    char local_ip[AT_ADDR_LEN] = {0};
    char remote_ip[AT_ADDR_LEN] = {0};
    struct at_socket *socket = RT_NULL;
    struct at_device *device = RT_NULL;
    char *client_name = client->device->parent.name;
    int peer_id, type, protocol, local_port, remote_port;
    
    RT_ASSERT(client && data && size);
    
#if W15_URC_MSG_SHOW_ENABLE
    LOG_D("get urc: %.*s", size, data);
#endif    
    
    device = at_device_get_by_name(AT_DEVICE_NAMETYPE_CLIENT, client_name);
    if (device == RT_NULL) {
        LOG_E("get device(%s) failed.", device->name);
        return;
    }
    
    if (rt_strstr(data, "+UUDPC")) {
        sscanf(data, "+UUDPC:%d,%d,%d,%[^,],%d,%[^,],%d", &peer_id, &type, &protocol, local_ip, &local_port, remote_ip, &remote_port);
        if (peer_id == 0) {
            LOG_W("device(%s) get error peer id, discard this connection.", device->name);
        } else if (protocol == 0 || protocol ==1) {
            LOG_D("%s(id:%d) connection %s:%d => %s:%d established.", protocol == 0 ? "TCP": "UDP", peer_id, local_ip, local_port, remote_ip, remote_port);
            //rt_thread_mdelay(100);
            w15_socket_event_send(device, SET_EVENT(peer_id, W15_EVENT_CONN_OK));
            
            /** make sure that tcp client is the LAST ONE to create
                check local port to designate peer_id to AT socket index
                the last AT socket created always be the tcp client **/
            if (local_port == 80) {
                if (w15_socket_fd[0] == -1) {
                    w15_socket_fd[0] = peer_id;
                } else if(w15_socket_fd[1] == -1) {
                    w15_socket_fd[1] = peer_id;
                } else {
                    w15_socket_fd[2] = peer_id;
                }
            } else {
                w15_socket_fd[3] = peer_id;
            }
            
        } else if (protocol == 6) {
            LOG_I("this is a MQTT connection ~_~");
        }
    } else if (rt_strstr(data, "+UUDPD")) {
        sscanf(data, "+UUDPD:%d", &peer_id);
        LOG_D("device(%s) connection peers(%d) failure or has been disconnected.", device->name, peer_id);
        w15_socket_event_send(device, SET_EVENT(peer_id, W15_EVENT_CONN_FAIL));
        
        for (int i = 0; i < AT_DEVICE_W15_SOCKETS_NUM; i++) {
            if (peer_id == w15_socket_fd[i]) {
                w15_socket_fd[i] = -1;
                /* notice the socket is disconnect by remote */
                socket = &(device->sockets[i]);
                if (at_evt_cb_set[AT_SOCKET_EVT_CLOSED]) {
                    at_evt_cb_set[AT_SOCKET_EVT_CLOSED](socket, AT_SOCKET_EVT_CLOSED, RT_NULL, 0);
                }
                
                break;
            }
        }
    }
}

static void urc_recv_func(struct at_client *client, const char *data, rt_size_t size)
{
    rt_thread_t tid;
    int device_socket = 0;
    rt_int32_t timeout = 0;
    static w15_recv_t recv_info;
    rt_size_t bfsz = 0, temp_size = 0;
    struct at_socket *socket = RT_NULL;
    struct at_device *device = RT_NULL;
    char *recv_buf = RT_NULL, temp[8] = {0};
    char *client_name = client->device->parent.name;

    RT_ASSERT(data && size);
    
#if W15_URC_MSG_SHOW_ENABLE
    LOG_D("get urc: %.*s", size, data);
#endif    
    
    device = at_device_get_by_name(AT_DEVICE_NAMETYPE_CLIENT, client_name);
    if (device == RT_NULL) {
        LOG_E("get device(%s) failed.", device->name);
        return;
    }

    /* get the at deveice socket and receive buffer size by receive data */
    sscanf(data, "+UUDATA:%d,%d:", &device_socket, (int *) &bfsz);
    
    if (bfsz <= 0) {
        return;
    }
    
    rt_mutex_take(&recv_urc_idct.lock, RT_WAITING_FOREVER);
    recv_urc_idct.peer_id[device_socket - 1] = bfsz;
    rt_mutex_release(&recv_urc_idct.lock);
}

static const struct at_urc urc_table[] =
{
    {"+UUDPC",           "\r\n",           urc_connect_func},
    {"+UUDPD",           "\r\n",           urc_connect_func},
    
    {"+UUDATA",          "\r\n",           urc_recv_func},
    {"AT+UDATR=",        "\r\n",           urc_recv_data_func},
};

int w15_socket_init(struct at_device *device)
{
    rt_thread_t tid;
    
    RT_ASSERT(device);
    
    /* register URC data execution function  */
    at_obj_set_urc_table(device->client, urc_table, sizeof(urc_table) / sizeof(urc_table[0]));
    
    for (int i = 0; i < AT_DEVICE_W15_SOCKETS_NUM; i++) {
        w15_socket_fd[i] = -1;
        recv_urc_idct.peer_id[i] = 0;
    }
    
    rt_mutex_init(&recv_urc_idct.lock, "recv_urc_lock", RT_IPC_FLAG_PRIO);
    
    tid = rt_thread_create( "w15_reqst_recv",
                            w15_reqst_data_thread, 
                            RT_NULL,
                            2048, 
                            18, 
                            5);
    if (tid != RT_NULL) {  
        rt_thread_startup(tid);
        LOG_D("w15 reqst data thread initialized.");
    } else {
        LOG_E("w15 reqst data thread initialized failed.");
    }
    
    return RT_EOK;
}

int w15_socket_class_register(struct at_device_class *class)
{
    RT_ASSERT(class);

    class->socket_num = AT_DEVICE_W15_SOCKETS_NUM;
    class->socket_ops = &w15_socket_ops;

    return RT_EOK;
}

/* these functions are for test w15 mudoule */
#if 1
static int w15_socket(int argc, char **argv)
{
    int sock_id;
    int result = RT_EOK;
    struct at_socket *sock;
    struct at_device *device = RT_NULL;
    char data[] = "1234567890123456789#";
    char recv_buffer[10] = {0};
   
    device = at_device_get_by_name(AT_DEVICE_NAMETYPE_NETDEV, W15_DEIVCE_NAME);
    if (device == RT_NULL) {
        LOG_E("device(%s) not found.", W15_DEIVCE_NAME);
        return result;
    }
    
    sock_id = at_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sock_id < 0) {
        LOG_E("get socket failed.");
        return RT_EOK;
    } else {
        LOG_I("sock_id is %d", sock_id);
    }    
    
    struct sockaddr_in sk;
    sk.sin_family = AF_INET;
    sk.sin_port = htons(222);
    sk.sin_addr.s_addr = inet_addr("10.110.50.23");
    if (at_connect(sock_id, (struct sockaddr *)&sk, sizeof(sk)) == RT_EOK) {
        at_send(sock_id, data, strlen(data), MSG_DONTWAIT);
        while (1) {
            sock = at_get_socket(sock_id);
            if (sock->state == AT_SOCKET_CLOSED) {
                at_closesocket(sock_id);
                break;
            }
            
            if (at_recv(sock_id, recv_buffer, sizeof(recv_buffer) - 1, 3 * RT_TICK_PER_SECOND) > 0) {
                LOG_I("\nget data from sock_id(%d):\n%s\n", sock_id, recv_buffer);
            }
                
            rt_thread_mdelay(500);
            rt_kprintf(".");
        }
    } else {
        LOG_E("connect failed.");
    }
    
    return result;
}
MSH_CMD_EXPORT(w15_socket, w15 device socket test);

static int domain(int argc, char **argv)
{
    int ret;
    char ip[16];
    
    ret = w15_domain_resolve(argv[1], ip);
    
    rt_kprintf("\nret is %d, ip is %s\n", ret, ip);
    return ret;
}
MSH_CMD_EXPORT(domain, w15 resolve domain);

static int socket_list(int argc, char **argv)
{
    rt_kprintf("w15_socket_fd[0] = %d\n", w15_socket_fd[0]);
    rt_kprintf("w15_socket_fd[1] = %d\n", w15_socket_fd[1]);
    
    return RT_EOK;
}
MSH_CMD_EXPORT(socket_list, show socket list map);

#endif

#endif /* AT_DEVICE_USING_W15 && AT_USING_SOCKET */

